import tkinter as tk
from tkinter import filedialog, messagebox
import os
import requests
import base64
import time

# 创建屏幕
window = tk.Tk()
window.geometry("500x500")
window.title('车辆识别')
# sport
sport = True
# 信息
data_Car = {}


# 定义写字方法
def write(text, x, y):
    fontLabel = tk.Label(window, text=text, font=('Airal', 23), bg='blue')
    fontLabel.place(x=x, y=y)


# 创建选择图片方法
def select_img():
    global sport
    img = filedialog.askopenfilename(initialdir='图片', title='CHOOSE AN IMG')
    if os.path.splitext(img)[1] not in ['.png', '.jpg', '.jpeg', '.PNG', '.JPG', '.JPEG'] or not sport:
        messagebox.showwarning(title='提示', message='未知错误')
    else:
        sport = False
        host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=UTlPAzlYWIGqlLqAxqGrILlf&client_secret=RLulINXoHnAeGPc0rTIxVmpslX5vIFCj'
        response = requests.get(host)
        if response:
            content = response.json()
        request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/car"
        # 二进制方式打开图片文件
        f = open(img, 'rb')
        img = base64.b64encode(f.read())

        params = {"image": img, "top_num": 5}
        access_token = content['access_token']
        request_url = request_url + "?access_token=" + access_token
        headers = {'content-type': 'application/x-www-form-urlencoded'}
        response = requests.post(request_url, data=params, headers=headers)
        time.sleep(1)
        if response:
            content = response.json()
            print(content)
            colour = content['color_result']
            year = content['result'][0]['year']
            name = content['result'][0]['name']
            data_Car['colour'] = colour
            data_Car['year'] = year
            data_Car['name'] = name
            write('颜色:' + data_Car['colour'], 50, 100)
            write('年份:' + data_Car['year'], 50, 150)
            write('名字:' + data_Car['name'], 50, 200)


# 新建按钮
choose_img = tk.Button(window, text='CHOOSE AN IMG', bg='red', bd=0, command=select_img)
choose_img.pack()


# 屏幕循环
window.mainloop()
